import axios from "axios"
import {ElMessage} from "element-plus";
import {useUserStore} from "@/store/user.ts";

// axios基础封装
const Request = axios.create({
    // 根域名
    baseURL: "http://116.62.147.119:3636",
    // 超时时间
    timeout: 5000
})

// axios请求拦截器
Request.interceptors.request.use(config => {
    // 加载效果
    // loadingInstance = ElLoading.service({
    //     text: '网络在开小差...',
    //     fullscreen: true,
    // })
    const userStore = useUserStore()
    const token = userStore.adminToken
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
Request.interceptors.response.use(res => {
    // loadingInstance.close()
    return res.data
}, e => {
    let message = ''
    const status = e.response.status
    switch (status) {
        case 401:
            message = "TOKEN过期"
            break
        case 403:
            message = "无权访问"
            break
        case 404:
            message = "请求地址错误"
            break
        case 500:
            message = "服务器错误"
            break
        default:
            message = e.response.data.error
            break
    }
    ElMessage({
        type: 'error',
        message
    })

    if (status === 401) {
        location.href = '/login'
    }
    return Promise.reject(e)
})

export default Request